package cn.linstudy.job;

import cn.linstudy.common.web.Result;
import cn.linstudy.domain.SeckillProductVo;
import cn.linstudy.feign.SeckillProductFeignApi;
import cn.linstudy.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Description 初始化秒杀商品
 * @Author XiaoLin
 * @Date 2021/5/16 18:42
 */
@Component
@Getter
@Setter
@Slf4j
public class InitSeckillProductJob implements SimpleJob {

  @Value("${jobCron.initSeckillProduct}")
  private String cron;

  @Autowired
  private StringRedisTemplate stringRedisTemplate;

  @Autowired
  private SeckillProductFeignApi seckillProductFeignApi;


  @Override
  public void execute(ShardingContext shardingContext) {
    doWork(shardingContext.getShardingParameter());
  }

  private void doWork(String time) {
    // 先清空Redis中缓存的数据
    stringRedisTemplate.delete(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time));
    stringRedisTemplate.delete(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time));
    // 从数据库中查询数据出来
    Result<List<SeckillProductVo>> listResult = seckillProductFeignApi
        .querySeckillProductVOSByTime(Integer.parseInt(time));
    // 查询出来的结果没问题
    if (listResult != null && !listResult.hasError()){
      List<SeckillProductVo> seckillProductVoList = listResult.getData();
      // 不为空才放进Redis
      if (seckillProductVoList!= null){
        for (SeckillProductVo seckillProductVo : seckillProductVoList) {
        stringRedisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),seckillProductVo.getId()+"",
            JSON.toJSONString(seckillProductVo));
        // 将库存放进redis
          stringRedisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time+""),seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");
        }
        log.info("数据初始化成功"+time);
      }
    }
  }

}
